<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>取消请求</title>
    <style>
        .result {
            width: 200px;
            height: 200px;
            border: 1px solid #000;
        }
    </style>
</head>

<body>
    <button>点击发送</button>
    <button>点击取消</button>
    <div class="result"></div>
    <script>
        //获取元素对象
        const btns = document.querySelectorAll('button');
        const result = document.querySelector('.result');
        let xhr = null;

        btns[0].onclick = function () {
            xhr = new XMLHttpRequest();
            xhr.open("GET", 'http://127.0.0.1:8000/delay');
            xhr.send();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        result.innerHTML = '请求成功！';
                    }
                }
            }
        }

        // abort
        btns[1].onclick = function () {
            xhr.abort();
            result.innerHTML = '取消请求成功！';
        }
    </script>
</body>

</html>